package a66weding.com.jiehuntong.activity.toolsbudget;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import org.greenrobot.eventbus.EventBus;
import java.util.ArrayList;
import java.util.HashMap;
import a66weding.com.jiehuntong.R;
import a66weding.com.jiehuntong.application.DataWareHourse;
import a66weding.com.jiehuntong.beans.BudgetBean;
import a66weding.com.jiehuntong.beans.CommonResultBean;
import a66weding.com.jiehuntong.beans.ErrorBean;
import a66weding.com.jiehuntong.beans.HttpRequestBean;
import a66weding.com.jiehuntong.beans.SuccessBean;
import a66weding.com.jiehuntong.common.CommonAdapter;
import a66weding.com.jiehuntong.common.MyViewHolder;
import a66weding.com.jiehuntong.common.utils.CUtils;
import a66weding.com.jiehuntong.common.utils.CacheUtils;
import a66weding.com.jiehuntong.common.utils.Tools;
import a66weding.com.jiehuntong.http.HttpHandleUtil;
import a66weding.com.jiehuntong.http.NetStatusUtil;
import a66weding.com.jiehuntong.http.OnNetResultListener;
import a66weding.com.jiehuntong.http.RequestCode;
import a66weding.com.jiehuntong.http.UrlDealUtil;
import a66weding.com.jiehuntong.view.ConfirmDialog;
import a66weding.com.jiehuntong.view.SwipteLayout2;
import static a66weding.com.jiehuntong.common.utils.CacheUtils.saveObjectToTextFile;
public class ToolsBudgetActivity extends BaseBudgetActivity implements View.OnClickListener, OnNetResultListener {
    private TextView mTitleTv;
    private TextView mBackTv;
    private TextView mHeadRightfuncTv;
    private LinearLayout mBackLay;
    private LinearLayout mSelectPlaceLay;
    private LinearLayout mNoNetLay;
    private LinearLayout mProgressLay;
    private LinearLayout mContentLay;
    private LinearLayout mEmptyLay;
    private ListView mBudgetLview;
    private TextView mMoneyCountTv;
    private Button mBudgetCommit;
    private TextView mAddBudgetTv;
    private SwipteLayout2 mSwipeLay;
    private ArrayList<BudgetBean.DataBean> budgetList;
    private CommonAdapter myAdapter;
    private BudgetBean budgetBean;
    private int mCurrentposition;
    private PopupWindow msgPopwindow;
    public static boolean ispopShow;
    private boolean isFromTools;
    protected static final int HAVEDATA = 1;
    protected static final int NODATA = 0;
    protected static final int DATAERROR = 2;
    protected static final int NONET = 4;
    public static boolean isNeedSave = false;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_tools_budget);
        isFromTools = getIntent().getBooleanExtra("isFromTools", false);
        isNeedSave = false;
        initview();
        initdata();
    }

    private void initview() {
        mTitleTv = (TextView) findViewById(R.id.tv_header_title);
        mBackTv = (TextView) findViewById(R.id.tv_header_backcontent);
        mBackLay = (LinearLayout) findViewById(R.id.llay_header_back);
        mSelectPlaceLay = (LinearLayout) findViewById(R.id.lay_header_place);
        mHeadRightfuncTv = (TextView) findViewById(R.id.tv_header_function);
        mNoNetLay = (LinearLayout) findViewById(R.id.lay_shoplist_nonet);
        mProgressLay = (LinearLayout) findViewById(R.id.progressBar_lay);
        mContentLay = (LinearLayout) findViewById(R.id.rlay_tools_budgetcontent);
        mEmptyLay = (LinearLayout) findViewById(R.id.llay_tools_gift_emptygift);
        mBudgetLview = (ListView) findViewById(R.id.lview_tools_budget);
        mMoneyCountTv = (TextView) findViewById(R.id.tv_tools_moneycount);
        mBudgetCommit = (Button) findViewById(R.id.btn_tools_budget_editcommit);
        mAddBudgetTv = (TextView) findViewById(R.id.tv_tools_gift_addgift);
        mHeadRightfuncTv.setVisibility(View.VISIBLE);
        mSelectPlaceLay.setVisibility(View.GONE);
        mProgressLay.setVisibility(View.VISIBLE);
        mTitleTv.setText("结婚预算");
        mHeadRightfuncTv.setText("编辑");
        mBackTv.setText("返回");
        mBackLay.setOnClickListener(this);
        mBudgetCommit.setOnClickListener(this);
        mAddBudgetTv.setOnClickListener(this);
        mHeadRightfuncTv.setOnClickListener(this);
        mNoNetLay.setOnClickListener(this);
        mBudgetLview.setDivider(null);
        mHeadRightfuncTv.setEnabled(false);

    }

    private void initdata() {
        if (isFromTools) {
            isNeedSave = true;
            //读取刚才保存的预算
            budgetBean = CacheUtils.readObjectFromTextFile(UrlDealUtil.getRealUrl(RequestCode.RETURN_WBITEMSYS), BudgetBean.class);
            if (budgetBean != null) {
                notifyViewLay(HAVEDATA);
                setAdapter(budgetBean);
                mHeadRightfuncTv.setEnabled(true);
            }
        } else {
            getBudgetData();
        }
    }

    //获取数据
    private void getBudgetData() {
        String url = UrlDealUtil.getRealUrl(RequestCode.RETURN_WBITEM);
        HttpRequestBean httpRequestBean = new HttpRequestBean(RequestCode.POSTEQUEST, url,
                this, BudgetBean.class, RequestCode.RETURN_WBITEM);
        HttpHandleUtil.executeCommonPost(this, httpRequestBean);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_tools_gift_addgift://添加预算
                Intent intent = new Intent(this, ToolsBudgetAddbudgetActivity.class);
                startActivity(intent);
                break;
            case R.id.btn_tools_budget_editcommit://保存
                commit();
                break;
            case R.id.tv_header_function://编辑
                Intent intent2 = new Intent(this, ToolsBudgetEditbudgetActivity.class);
                Bundle bundle = new Bundle();
                bundle.putSerializable("budgetBean", budgetBean);
                intent2.putExtras(bundle);
                startActivityForResult(intent2, GETBUDGETRESULTCODE);
                break;
            case R.id.llay_header_back://返回
                onBackPressed();
                break;
            case R.id.lay_shoplist_nonet://无网点击重试
                getBudgetData();
                break;
            case R.id.btn_delete://删除item
                isNeedSave = true;
                mCurrentposition = (int) view.getTag();
                budgetList.remove(mCurrentposition);
                freshMoney();
                if (myAdapter != null) {
                    myAdapter.notifyDataSetChanged();
                }
                if (mSwipeLay != null) {
                    mSwipeLay.closeMenu();
                }
                break;
        }
    }

    @Override
    public void onSucess(SuccessBean sucessbean) {
        if (mCommitpop != null) {
            mCommitpop.dismiss();
        }
        Object data = sucessbean.getData();
        if (data instanceof BudgetBean) {
            budgetBean = (BudgetBean) data;
            switch (budgetBean.getResCode()) {
                case "0000":
                    notifyViewLay(HAVEDATA);
                    setAdapter(budgetBean);
                    mHeadRightfuncTv.setEnabled(true);
                    if (budgetBean != null) {
                        int moneyAccount = 0;
                        for (int i = 0; i < budgetBean.getData().size(); i++) {
                            moneyAccount += budgetBean.getData().get(i).getWBItemAmount();
                        }
                        budgetBean.setMoneyCount(moneyAccount);
                        saveObjectToTextFile(UrlDealUtil.getRealUrl(RequestCode.RETURN_WBITEMSYS), budgetBean);
                    }
                    break;
                default:
                    notifyViewLay(NODATA);
                    break;
            }

        } else if (data instanceof CommonResultBean) {
            CommonResultBean commonResult = (CommonResultBean) data;
            switch (commonResult.getResCode()) {
                case "0000":
                    notifyViewLay(HAVEDATA);
                    if (!isNeedSave){
                        ToolsBudgetActivity.this.finish();
                    }
                    //保存
                    CacheUtils.saveObjectToTextFile(UrlDealUtil.getRealUrl(RequestCode.RETURN_WBITEMSYS), budgetBean);
                    //更新内存
                    DataWareHourse.getInstance().getmUser().getData().get(0).setI_BudgetMoney(Double.valueOf(budgetBean.getMoneyCount()));
                    //更新内存
                    DataWareHourse.getInstance().getmUser().getData().get(0).setI_BudgetTables(Integer.valueOf(budgetBean.getBudgetTables()));
                    //更新本地缓存
                    CacheUtils.saveObjectToTextFile(RequestCode.TOLOGIN_ACTIVITY_REQUESTCODE, DataWareHourse.getInstance().getmUser());
                    break;
                default:
                    notifyViewLay(NODATA);
                    break;
            }
        }

    }

    @Override
    public void onError(ErrorBean errorBean) {
        if (mCommitpop != null) {
            mCommitpop.dismiss();
        }
        if (errorBean.getRequestCode().equals(RequestCode.SAVE_WBITEM)){
            isNeedSave=true;
        }
        mHeadRightfuncTv.setEnabled(false);
        switch (errorBean.getErrorCode()) {
            case ErrorBean.TIMEOUT:
                notifyViewLay(NONET);
                break;
            case ErrorBean.NONET:
                notifyViewLay(NONET);
                break;
            default:
                CUtils.showDataErrToast(this);
        }
    }

    private void setAdapter(BudgetBean mBudgitBean) {
        budgetList = mBudgitBean.getData();
        if (budgetList != null && budgetList.size() > 0) {
            freshMoney();
            myAdapter = new CommonAdapter<BudgetBean.DataBean>(this, budgetList, R.layout.item_tools_budget_contentitem) {
                @Override
                public void convert(MyViewHolder holder, int position) {
                    BudgetBean.DataBean dataBean = budgetList.get(position);
                    holder.setText(R.id.name, dataBean.getWBItemName());
                    TextView moneyItemTv = (TextView) holder.getView(R.id.tv_tools_budgetmoney);
                    TextView moneyItemTv_1 = (TextView) holder.getView(R.id.tv_me_contentitem_1);
                    TextView moneyItemTv_2 = (TextView) holder.getView(R.id.tv_me_contentitem_2);
                    TextView moneyItemTv_3 = (TextView) holder.getView(R.id.tv_me_contentitem_3);
                    LinearLayout mShowLay = (LinearLayout) holder.getView(R.id.ll_me_contentitem);
                    Button mDelBtn = (Button) holder.getView(R.id.btn_delete);
                    SwipteLayout2 mSwipLay = (SwipteLayout2) holder.getView(R.id.llay_tools_dayplan_mainitem);
                    if (position == 0) {
                        moneyItemTv.setVisibility(View.GONE);
                        mShowLay.setVisibility(View.VISIBLE);
                        int money = dataBean.getWBItemAmount() / budgetBean.getBudgetTables();
                        int table = budgetBean.getBudgetTables();
                        moneyItemTv_1.setText("每桌金额" + money);
                        moneyItemTv_2.setText("桌数" + table);
                        moneyItemTv_3.setText("" + dataBean.getWBItemAmount());
                        mDelBtn.setVisibility(View.GONE);
                    } else {
                        moneyItemTv.setVisibility(View.VISIBLE);
                        mShowLay.setVisibility(View.GONE);
                        moneyItemTv.setText("" + dataBean.getWBItemAmount());
                    }
                    mSwipLay.setOnItemStateChanged(new SwipteLayout2.OnItemStateChanged() {
                        @Override
                        public void onOpen(SwipteLayout2 layout) {
                            mSwipeLay = layout;
                        }

                        @Override
                        public void onClose(SwipteLayout2 layout) {
                            if (mSwipeLay == layout) {
                                mSwipeLay = null;
                            }
                        }

                        @Override
                        public void onDown(SwipteLayout2 layout) {
                            if (mSwipeLay != null && mSwipeLay != layout) {
                                mSwipeLay.closeMenu();
                            }
                        }
                    });
                    mDelBtn.setTag(position);
                    mDelBtn.setOnClickListener(ToolsBudgetActivity.this);
                }
            };
            mBudgetLview.setAdapter(myAdapter);
        }
    }

    private void commit() {
        showCommitPopupWindow(this, mBudgetCommit);
        String url = UrlDealUtil.getRealUrl(RequestCode.SAVE_WBITEM);
        HashMap<String, String> requestParams = new HashMap<String, String>();
        StringBuffer persontsb = new StringBuffer();
        StringBuffer temAmountsb = new StringBuffer();
        StringBuffer temNamesb = new StringBuffer();
        int tableCount = budgetBean.getBudgetTables();
        int moneyCount = 0;
        if (budgetList.size() > 0) {
            for (int i = 0; i < budgetList.size(); i++) {
                BudgetBean.DataBean dataBean = budgetList.get(i);
                if (i == budgetList.size() - 1) {
                    persontsb.append(dataBean.getPersent() + "");
                    temAmountsb.append(dataBean.getWBItemAmount() + "");
                    temNamesb.append(dataBean.getWBItemName() + "");
                } else {
                    persontsb.append(dataBean.getPersent() + ",");
                    temAmountsb.append(dataBean.getWBItemAmount() + ",");
                    temNamesb.append(dataBean.getWBItemName() + ",");
                }
                moneyCount += dataBean.getWBItemAmount();
            }

            requestParams.put("BudgetTables", "" + tableCount);
            requestParams.put("BudgetMoney", String.valueOf(moneyCount));
            requestParams.put("Persent", "" + persontsb.toString());
            requestParams.put("WBItemAmount", "" + temAmountsb.toString());
            requestParams.put("WBItemName", "" + temNamesb.toString());

        } else {
            requestParams.put("BudgetTables", "" + tableCount);
            requestParams.put("Persent", "");
            requestParams.put("BudgetMoney", "0");
            requestParams.put("WBItemAmount", "");
            requestParams.put("WBItemName", "");
        }
        HttpRequestBean budgithttp = new HttpRequestBean(RequestCode.POSTEQUEST, url, this,
                CommonResultBean.class, RequestCode.SAVE_WBITEM, requestParams);
        HttpHandleUtil.executeCommonPost(this, budgithttp);
        isNeedSave=false;
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        ispopShow = true;
    }

    private void notifyViewLay(int state) {
        switch (state) {
            case HAVEDATA:
                mProgressLay.setVisibility(View.GONE);
                if (mContentLay.isShown()) {
                    return;
                }
                mContentLay.setVisibility(View.VISIBLE);
                mEmptyLay.setVisibility(View.GONE);
                mHeadRightfuncTv.setVisibility(View.VISIBLE);
                mNoNetLay.setVisibility(View.GONE);
                break;
            case NODATA:
                mProgressLay.setVisibility(View.GONE);
                mContentLay.setVisibility(View.GONE);
                mEmptyLay.setVisibility(View.VISIBLE);
                mHeadRightfuncTv.setVisibility(View.GONE);
                mNoNetLay.setVisibility(View.GONE);
                break;
            case NONET:
                mNoNetLay.setVisibility(View.VISIBLE);
                mProgressLay.setVisibility(View.GONE);
                mContentLay.setVisibility(View.GONE);
                mEmptyLay.setVisibility(View.GONE);

                break;
        }
    }
    public void showDialog(Context context, String title, String confirm, String cancel) {
        final ConfirmDialog confirmDialog = new ConfirmDialog(context, title, confirm, cancel, R.layout.confirm_dialog);
        confirmDialog.show();
        confirmDialog.setClicklistener(new ConfirmDialog.ClickListenerInterface() {
            @Override
            public void doConfirm() {
                confirmDialog.dismiss();

            }

            @Override
            public void doCancel() {
                confirmDialog.dismiss();
            }
        });
    }
    public void showCommitDialog(Context context, String title, String confirm, String cancel) {
        final ConfirmDialog confirmDialog = new ConfirmDialog(context, title, confirm, cancel, R.layout.confirm_dialog);
        confirmDialog.show();
        confirmDialog.setClicklistener(new ConfirmDialog.ClickListenerInterface() {
            @Override
            public void doConfirm() {
                confirmDialog.dismiss();
            }
            @Override
            public void doCancel() {
                confirmDialog.dismiss();
            }
        });
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == GETBUDGETRESULTCODE) {
            if (data != null) {
                budgetBean = (BudgetBean) data.getExtras().getSerializable("budgetbean");
                if (budgetBean != null) {
                    setAdapter(budgetBean);
                }
            }
        }
    }
    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        if (hasFocus && !ispopShow && !super.isshowed()) {
            showPopupWindow(mBackLay);
            super.setIsshowed(true);
            ispopShow = true;
        }
    }
    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }
    private void showPopupWindow(View view) {
        View contentView = LayoutInflater.from(this).inflate(
                R.layout.pop_tools_dayplan_msg, null);
        msgPopwindow = new PopupWindow(contentView,
                ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT, true);
        msgPopwindow.setFocusable(true);
        ImageView button = (ImageView) contentView.findViewById(R.id.iv_delete);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                msgPopwindow.dismiss();
            }
        });

        contentView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                msgPopwindow.dismiss();
            }
        });
        //点击空白处时，隐藏掉pop窗口
        msgPopwindow.setTouchable(true);
        msgPopwindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        //设置位置
        msgPopwindow.showAtLocation(view, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
        msgPopwindow.showAsDropDown(view);
    }
    public void freshMoney() {
        if (budgetList != null) {
            int moneyAccount = 0;
            for (int i = 0; i < budgetList.size(); i++) {
                moneyAccount += budgetList.get(i).getWBItemAmount();
            }
            mMoneyCountTv.setText(" ￥" + moneyAccount);
        }
    }
    @Override
    public void onBackPressed() {
        Log.i("是否", "onBackPressed: "+isNeedSave);
        if (isNeedSave) {
            Tools.showSimpleDialog(this, "是否保存预算", "否", "是", new Tools.ClickListenerInterface() {
                @Override
                public void doConfirm() {
                    Log.i("是否", "doConfirm: ");
                    commit();
                }
                @Override
                public void doCancel() {
                    finish();
                }
            });
        } else {
            super.onBackPressed();
        }
    }
}
